<template>
    <!-- 查询 -->
    <el-form :inline="true" :model="queryData">

        <template v-for="item in queryConfig" :key="item.id">

            <!-- 输入框 -->
            <el-form-item v-if="!item.type || item.type == 'text'" :label="item.label">
                <el-input v-model="queryData[item.field]" :placeholder="'请输入' + item.label" />
            </el-form-item>

        </template>

        <!-- 按钮 -->
        <template v-if="queryConfig.length">
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="getData">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="" :icon="RefreshRight" @click="reset">重置</el-button>
            </el-form-item>
        </template>
        <el-form-item>
            <el-button type="primary" :icon="Plus" @click="add">新增</el-button>
        </el-form-item>

    </el-form>

    <!-- 表格 -->
    <el-table :data="tableData" v-loading="loading" table-layout="auto" height="calc(100vh - 184px)" stripe class="el-table">

        <template v-for="item in props.config.data" :key="item.id">

            <!-- 字典 -->
            <el-table-column v-if="item.type == 'select'" :label="item.label">
                <template #default="scope">
                    <template v-for="opt in item.options">
                        <template v-if="scope.row[item.field] == opt.value">{{ opt.label }}</template>
                    </template>
                </template>
            </el-table-column>

            <!-- 图片 -->
            <el-table-column v-else-if="item.type == 'image'" :label="item.label">
                <template #default="scope">
                    <!-- <el-image style="width: 80px; height: 80px" :src="baseURL + scope.row[item.prop]" fit="contain" /> -->
                    <img style="width: 80px; height: 80px" :src="baseURL + scope.row[item.field]">
                </template>
            </el-table-column>
           <!-- 是否是会员 -->
             <el-table-column v-else-if="item.type == 'vip'" :label="item.label">
                <template #default="scope">
                    <span v-if="scope.row[item.field]">是</span>
                    <span v-else>否</span>
                </template>
            </el-table-column>
            <!-- 默认 -->
            <el-table-column v-else :prop="item.field" :label="item.label" />

        </template>

        <el-table-column v-if="props.config.API.edit || props.config.API.del" fixed="right" label="操作" width="140">
            <template #default="scope">
                <el-button v-if="props.config.API.edit" link type="primary" size="small" :icon="Edit"
                    @click="edit(scope.row)">编辑</el-button>
                <el-popconfirm v-if="props.config.API.del" title="确认删除此项?" confirm-button-text="确认" cancel-button-text="取消"
                    @confirm="del(scope.row.id)">
                    <template #reference>
                        <el-button link type="danger" size="small" :icon="Delete">删除</el-button>
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination background layout="prev, pager, next" :total="count" @change="pageChange" />

    <!-- 表单 -->
    <el-dialog v-model="visible" title="添加/编辑" width="600">
        <el-form :model="formData" ref="formRef" :rules="rules">

            <template v-for="item in formConfig" :key="item.id">

                <!-- 文本 -->
                <el-form-item v-if="!item.type || item.type == 'text'" :label="item.label" :prop="item.field"
                    :label-width="labelWidth">
                    <el-input v-model="formData[item.field]" :placeholder="'请输入' + item.label" clearable />
                </el-form-item>

                <!-- 文本域 -->
                <el-form-item v-if="item.type == 'textarea'" :label="item.label" :prop="item.field"
                    :label-width="labelWidth">
                    <el-input v-model="formData[item.field]" :rows="2" type="textarea" :placeholder="'请输入' + item.label"
                        clearable />
                </el-form-item>

                <!-- 密码框 -->
                <el-form-item v-if="item.type == 'password'" :label="item.label" :prop="item.field"
                    :label-width="labelWidth">
                    <el-input v-model="formData[item.field]" :placeholder="'请输入' + item.label" show-password clearable />
                </el-form-item>

                <!-- 选择 -->
                <el-form-item v-if="item.type == 'select'" :label="item.label" :prop="item.field" :label-width="labelWidth">
                    <el-select v-model="formData[item.field]" :placeholder="'请选择' + item.label" style="width: 240px">
                        <el-option v-for="item in item.options" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>

                <!-- 数字框 -->
                <el-form-item v-if="item.type == 'number'" :label="item.label" :prop="item.field" :label-width="labelWidth">
                    <el-input-number v-model="formData[item.field]" :precision="item.precision || 0" />
                </el-form-item>

                <!-- 上传 -->
                <el-form-item v-if="item.type == 'image'" :label="item.label" :label-width="labelWidth">
                    <el-upload class="avatar-uploader" :action="uploadURL" :show-file-list="false" name="file"
                        accept="image/*" :on-success="(res) => formData[item.field] = res.src">
                        <img v-if="formData[item.field]" :src="baseURL + formData[item.field]" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

            </template>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="visible = false">关闭</el-button>
                <el-button type="primary" @click="submit(formRef)">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- <Pagination :total="total" @changeSize="handlerChangeSize" @changeCurrent="handlerChangeCurrent" class="position" /> -->
</template>
  
<script setup>
import { ref, defineProps } from 'vue'
import { Search, RefreshRight, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { baseURL, uploadURL } from "@/api/config.json"
import Pagination from "@/components/Pagination.vue";
const props = defineProps({
    config: {
        type: Object,
        default: () => {
            return {
                API: {
                    get: Promise.resolve(),
                    add: Promise.resolve(),
                    edit: Promise.resolve(),
                    del: Promise.resolve(),
                },
                data: []
            }
        }
    }
})
const total = ref(0);
const handlerChangeSize = (size) => {
  queryData.pageSize = size;
  getData();
};
const handlerChangeCurrent = (num) => {
  queryData.pageNum = num;
  getData();
};
const content = ref();
const getMsg = (val) => {
  formData.value.content = val;
};
const labelWidth = 110
const clear = (obj) => {
    for (const key in obj) {
        queryData.value[key] = ""
    }
}

// 查询
const queryData = ref({})
const queryConfig = ref(props.config.data.filter(i => i.query))
const reset = () => {
    clear(queryData.value)
    getData()
}

// 列表
const page = ref(1)
const count = ref()
const loading = ref(false)
const tableData = ref([])

const getData = () => {
  
    if (!props.config.API.get) return console.log('required API.get method');
    loading.value = true
    let token = localStorage.getItem('token')
    let queryParams = ''
    if (queryData.value.phone_number == '' ) {
        queryParams = Object.assign({user_token: token })
    } else {
        queryParams = Object.assign(queryData.value, {user_token: token })
    }
    props.config.API.get(queryParams)?.then((res) => {
        console.log(res, '获取人员')
        tableData.value = res.data.items
        loading.value = false
        count.value = res.data.total_count
    }
    )
    
}

getData()

const pageChange = (currentPage) => {
    page.value = currentPage
    getData()
}

// 新增/编辑
const visible = ref(false)
const formRef = ref()
const formData = ref({})
const formConfig = ref(props.config.dataVip.filter(i => i.operate))
const rules = ref({})
props.config.data.map(item => {
    if (item.required) {
        rules.value[item.field] = [
            {
                required: true,
                message: `${item.type == 'select' ? '请选择' : '请输入'}${item.label}`,
                trigger: 'blur'
            }
        ]
    }
})

const add = () => {
    clear(formData.value)
    visible.value = true
}

const edit = (row) => {
    formData.value = { ...row }
    visible.value = true
}

const submit = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid) => {
        if (valid) {
            const data = { ...formData.value }
            let token = localStorage.getItem('token')
            data.user_token = token
            const API = data.id ? props.config.API.edit : props.config.API.add
            data.user_id = data.id
            console.log(props.config.API.edit, props.config.API.add)
            API(data).then((res) => {
                if (res.code == 0) {
                    visible.value = false
                    ElMessage.success('操作成功')
                    getData()
                } else {
                    ElMessage.error(res.message)
                }
            })
        }
    })
}


// 删除
const del = (id) => {
    let token = localStorage.getItem('token')
    props.config.API.del({ user_id: id, user_token: token }).then((res) => {
        if (res.code == 0) {
            ElMessage.success('删除成功')
            getData()
        } else {
            ElMessage.error(res.msg)
        }
    })
}


</script>
<style scoped>
.el-pagination {
    margin-top: 18px;
    justify-content: flex-end;
}

:deep(.cell img) {
    width: 100px !important;
    height: 100px !important;
}

:deep(.avatar-uploader .avatar) {
    width: 120px;
    height: 120px;
    display: block;
}

:deep(.avatar-uploader .el-upload) {
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: .2s;
}

:deep(.avatar-uploader .el-upload:hover) {
    border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
}
.position{
    position: fixed;
    bottom: 0;
}
.el-table{
    height: 700px;
}
</style>
  